package com.fjec.common.zk;

import com.fjec.common.Const;
import org.apache.curator.framework.CuratorFramework;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;

import java.util.List;

public class ZkDatacenterIdAndWorkerIdHelper {

    private CuratorFramework curator;

    public ZkDatacenterIdAndWorkerIdHelper(CuratorFramework curator) {
        this.curator = curator;
    }

    /**
     * @param path
     * @param value
     * @return 1=正常创建 2=节点已存在 3=其他异常无法创建
     */
    public int createNode(String path, String value, CreateMode createMode) {
        int result = 3;
        try {
            curator.create().creatingParentsIfNeeded()
                    .withMode(createMode)
                    .forPath(path, value.getBytes());
            result = 1;
        } catch (Exception e) {
            if (e instanceof KeeperException.NodeExistsException) {
                result = 2;
            }
        }
        return result;
    }

    /**
     * 生成Id配置
     *
     * @param ip
     * @return
     * @throws Exception
     */
    public int computeDataCenterAndWorkId(String ip) throws Exception {
        int childPath = -1;
        int result;
        do {
            List<String> nodePathList = curator.getChildren().forPath(Const.ZK_DATACENTERID_AND_WORKERID_ROOT);
            nodePathList.sort((o1, o2) -> Integer.parseInt(o1) - Integer.valueOf(o2));
            int i = 0;
            boolean findBreak = false;
            for (String nodePath : nodePathList) {
                if (Integer.parseInt(nodePath) > i) {
                    findBreak = true;
                    break;
                }
                i++;
            }
            childPath = findBreak ? i : i + 1;
            if (childPath > 1023) {
                throw new Exception("Zookeeper节点已满");
            }
            result = createNode(Const.ZK_DATACENTERID_AND_WORKERID_ROOT + "/" + childPath, ip, CreateMode.EPHEMERAL);
        } while (result == 2);
        return childPath;
    }
}
